// import React from 'react'
// import { Button, Checkbox, Form, Input, Select, Space, Table, Tag, Modal } from 'antd'
// import "./company.scss"
// import { useState, useEffect } from 'react';
// import api from '../../api';

// export default function Company() {

//   const [tableDatas, setTableDatas] = useState([])

//   const [pageParams, setPageParams] = useState({
//     page: '1',
//     size: '3',
//     order: "createTime",
//     sort: "desc"
//   })

//   useEffect(() => {
//     getCompanys()
//   }, [])

//   //获取餐饮单位列表接口
//   const getCompanys = async() => {
//     const data = await api.getCompanys(pageParams)
//     console.log(data);
//     setTableDatas(data.list)
//   }

//   const columns = [
//     {
//       // 表头标题
//       title: "序号",
//       // 代表那个字段
//       dataIndex: "name",
//       key: "id",
//       // 自定义渲染函数
//       render: (text, item, index) => <a>{index + 1}</a>,
//     },
//     {
//       title: "所属辖区",
//       dataIndex: "areaName",
//       key: "id",
//     },
//     {
//       title: "经营类型",
//       dataIndex: "businessType",
//       key: "id",
     
//     },

//     {
//       title: "门店名称",
//       dataIndex: "storeName",
//       key: "id",
//     },
//     {
//       title: "单位名称",
//       dataIndex: "companyName",
//       key: "id",
//     },
//     {
//       title: "许可证号",
//       dataIndex: "licenceNum",
//       key: "id",
//     },
//     {
//       title: "许可有效期",
//       dataIndex: "address",
//       key: "address",
     
//     },
//     {
//       title: "操作",
//       key: "action",
//       render: (_, record) => (
//         <Space size="middle">
//           <Button >编辑</Button>
//           <Button danger>删除</Button>
//         </Space>
//       ),
//     },
//   ];

//   //新增 
//   const [isModalOpen, setIsModalOpen] = useState(false);

//   const showModal = () => {
//     setIsModalOpen(true);
//   };

//   const handleOk = () => {
//     setIsModalOpen(false);
//   };

//   const handleCancel = () => {
//     setIsModalOpen(false);
//   };

//   //下拉菜单


//   return (
//     <div>
//       <div className='company-nav'>
//         <Space>
//           <Button onClick={showModal}>新增</Button>
//           <Button>刷新</Button>
//           <Button danger>删除</Button>
//           <div>
//             <Form className='company-nav' layout='inline'>
//               <Form.Item
//                 label="所属辖区"
//                 name="q"
//               >
//                 <Select

//                   style={{
//                     width: 120,
//                   }}

//                 >
//                   <Option value="jack">Jack</Option>
//                   <Option value="lucy">Lucy</Option>

//                 </Select>
//               </Form.Item>
//               <Form.Item
//                 label="经营类型
//             "
//               >
//                 <Select

//                   style={{
//                     width: 120,
//                   }}

//                 >
//                   <Option value="jack">Jack</Option>
//                   <Option value="lucy">Lucy</Option>

//                 </Select>
//               </Form.Item>
//               <Form.Item
//                 label="许可状态
//             "
//                 name="w"
//               >
//                 <Select

//                   style={{
//                     width: 120,
//                   }}

//                 >
//                   <Option value="jack">Jack</Option>
//                   <Option value="lucy">Lucy</Option>

//                 </Select>
//               </Form.Item>
//               <Space>
//                 <Form.Item>
//                   <Input type="text" style={{ width: "200PX", height: "30px" }} />
//                 </Form.Item>
//                 <Button type='primary' htmlType='submit'>搜索</Button>
//                 <Button danger type='button' >重置</Button>
//               </Space>
//             </Form>
//           </div>
//         </Space>
//       </div>
//       {/* 下拉菜单 */}
//       <Modal title="Basic Modal" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
//         <Form>
//           <Form.Item
//             label="监督检查"
//             name="q"
//           >
//             <Select

//               style={{
//                 width: 200,
//               }}

//             >
//               <Option value="jack">Jack</Option>
//               <Option value="lucy">Lucy</Option>

//             </Select>
//           </Form.Item>
//         </Form>
//       </Modal>

//       <Table style={{ margin: "20px 10px" }} columns={columns} dataSource={tableDatas} />;
//     </div>
//   )
// }


import React, { useState, useEffect } from 'react'
import { Button, Form, Input, Modal, Select, Space, Table,DatePicker } from 'antd'
import "./company.scss"
import api from '../../api'
import { businessTypeOptions, findBusinessTypeOptionLable, getPageInfo } from "./company.config"
import { fomatterData } from "./../../utils/fomatter-date"
import { ExclamationCircleOutlined } from "@ant-design/icons";
// import UploadImage from "./../../components/COS-upload/upload-image";
import moment from "moment";

const { confirm } = Modal;
const { RangePicker } = DatePicker;

const dateFormat = "YYYY/MM/DD";


export default function Company() {
  const [fromFilter] = Form.useForm()
  const [formUpdate] = Form.useForm();

  const [tableDatas, setTableDatas] = useState([]);

  const [pageParams, setPageParams] = useState(getPageInfo())

  const [delIds, setDelIds] = useState([]);

  //过滤参数
  const [filterParams, setFilterParams] = useState({})

  const [total, setTotal] = useState(0)

  const [areas, setAreas] = useState([])

  const [isModalOpen, setIsModalOpen] = useState(false)

  const [imgUrl, setImgUrl] = useState("");

  //  监听过滤参数的变化
  useEffect(() => {
    setPageParams({
      page: 1,
      size: 5,
      order: "createTime",
      sort: "desc"
    })
  }, [filterParams]);

  //分页控制器
  const paginationChange = (page, pageSize) => {
    //
    // console.log(page);
    setPageParams({ ...pageParams, page });
  }

  //获取所属辖区
  const getAreas = async () => {
    const data = await api.getAreas();
    setAreas(data)

  }
 /**
   * 点击编辑按钮
   * 获取详情，并打开弹框
   */
  const getDataDetail = async (id) => {
    // 获取详情数据
    const data = await api.getCompanyInfo(id);
    console.log(data);

    // 转换数据类型
    data.areaId = data.areaId && Number(data.areaId);

    // 转换时间数据
    data.validTime = [
      moment(data.validStartTime, dateFormat),
      moment(data.validEndTime, dateFormat),
    ];

    // 照片单独处理
    setImgUrl(data.sotreImage);

    // 回显表单数据
    formUpdate.setFieldsValue(data);

    // 打开弹框
    setIsModalOpen(true);
  };

  useEffect(() => {
    getAreas()
  }, [])

  //获取餐饮单位列表参数
  const getCompanys = async () => {
    const data = await api.getCompanys({ ...pageParams, ...filterParams });
    data.list.forEach(item => {
      item.key = item.id
    });
    setTableDatas(data.list);
    setTotal(data.pagination.total)
  }
  const columns = [
    {
      // 表头标题
      title: "序号",
      // 代表那个字段
      dataIndex: "name",
      key: "id",
      // 自定义渲染函数
      render: (text, item, index) => <a>{index + 1}</a>,
    },
    {
      title: "所属辖区",
      dataIndex: "areaName",
      key: "id",
    },
    {
      title: "经营类型",
      dataIndex: "businessType",
      key: "id",
      render: (text, item) => {
        return findBusinessTypeOptionLable(item.businessType);
      },
    },

    {
      title: "门店名称",
      dataIndex: "storeName",
      key: "id",
    },
    {
      title: "单位名称",
      dataIndex: "companyName",
      key: "id",
    },
    {
      title: "许可证号",
      dataIndex: "licenceNum",
      key: "id",
    },
    {
      title: "许可有效期",
      dataIndex: "address",
      key: "address",
      render: (text, item) => {
        return `${fomatterData(item.validStartTime)}-${fomatterData(
          item.validEndTime
        )}`;
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button  onClick={() => getDataDetail(record.id)}>编辑</Button>
          <Button danger onClick={() => delData(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 许可状态
  const validStatusOptions = [
    {
      label: "全部",
      value: "",
    },
    {
      label: "正常",
      value: "NORMAL",
    },
    {
      label: "过期",
      value: "BEOVERDUE",
    },
    {
      label: "临近过期",
      value: "NEAREXPIRATION",
    },
  ];

  //搜索
  const filterChange = (value) => {
    // setFilterParams(value);
    setFilterParams(value)
  };

  //重置
  const resetFilter = () => {
    fromFilter.resetFields()
  }


  /**
   * 渲染地区select
   * @param {*} isFilter
   * @returns
   */
  const areaSelectRender = (isFilter) => {
    // 判断是否是顶栏的过滤option
    const currentAreas = isFilter
      ? [{ name: "全部", id: "" }, ...areas]
      : areas;

    return (
      <Select
        style={{
          width: 120,
        }}
      >
        {currentAreas.map((item, index) => (
          <Option value={item.id} key={index}>
            {item.name}
          </Option>
        ))}
        ;
      </Select>
    );
  };

  /**
   * 顶栏的经营类型的下拉框
   * @param {*} isFilter
   * @returns
   */
  const businessSelectRender = (isFilter) => {
    /**
     * 如果是顶栏过滤的话则直接使用原数据
     * 如果是form里面的话则过滤掉全部
     */
    const currentBusinessTypeOptions = isFilter
      ? businessTypeOptions
      : businessTypeOptions.filter((item) => item.label !== "全部");
    return (
      <Select
        style={{
          width: 120,
        }}
      >
        {currentBusinessTypeOptions.map((item) => (
          <Option value={item.value} key={item.label}>
            {item.label}
          </Option>
        ))}
      </Select>
    );
  };

  const uploadSuccess = (url) => {
    console.log(url, "我是当前的地址");
    setImgUrl(url);
  };

  useEffect(() => {
    getCompanys()
  }, [pageParams])

  //table变化的回调
  const tableSelectionChange = (ids) => {
    setDelIds(ids);
  };

  const delData = (id) => {
    confirm({
      title: "确认删除该数据吗？",
      icon: <ExclamationCircleOutlined />,
      async onOk() {

        /**
         * 判断一下
         * 如果是单删，则会把当前要删除的id传过来
         * 多删，则不会传任何值
         */
        const ids = id ? [id] : delIds

        // 把我们要删除的数据传给后端
        await api.delCompany({ ids })

        // 把我们的分页数据重置，并且会重新调用接口
        setPageParams(getPageInfo())

        // 重置删除所选的id为空
        setDelIds([]);
      },
    });
  };

  const handleOk = async () => {
    // 获取表单的数据
    const data = formUpdate.getFieldsValue(true);
    console.log(data);

    // 在调接口之前对我们拿到的参数做一些相关的操作
    if (data.validTime) {
      data.validStartTime = fomatterData(data.validTime[0]);
      data.validEndTime = fomatterData(data.validTime[1]);
    }

    // 把我们的图片那放入data里面
    data.sotreImage = imgUrl;

    console.log(data);

    // 调用创建接口
    await api[data.id ? "updateCompany" : "createCompany"](data);

    // 重置分页数据，并重新调用数据接口
    setFilterParams({ ...filterParams, ...getPageInfo() });

    // 重置表单的数据
    formUpdate.resetFields();
    // 关闭弹框
    setIsModalOpen(false);
  };

    //取消按钮
  const handleCancel = () => {
    formUpdate.resetFields();
    // 关闭弹框
    setIsModalOpen(false);
  };

  return (
    <div id='company'>
      <div className='filter-box'>
        <Space>
          <Button type='ghost' onClick={getCompanys}>刷新</Button>
          <Button type='primary' onClick={() => setIsModalOpen(true)}>新增</Button>
          <Button type="primary" onClick={() => delData()} disabled={delIds.length === 0}>删除</Button>

          <Form form={fromFilter} layout='inline' onFinish={filterChange}>
            <Form.Item label="所属辖区" name="areaId" >
              <Select
                style={{
                  width: 120,
                }}
              >
                <Option value={''}>全部</Option>
                {
                  areas.map(item => (
                    <Option value={item.id} key={item.id}>{item.name} </Option>
                  ))
                }
              </Select>
            </Form.Item>
            <Form.Item label="经营类型" name="businessType" >
              <Select
                style={{
                  width: 120,
                }}
              >

                {
                  businessTypeOptions.map((item) => (
                    <Option value={item.value} key={item.value}>{item.label} </Option>
                  ))
                }
              </Select>
            </Form.Item>
            <Form.Item label="许可状态" name="validStatus" >
              <Select
                style={{
                  width: 120,
                }}
              >
                {
                  validStatusOptions.map((item) => (
                    <Option value={item.value} key={item.label}>{item.label} </Option>
                  ))
                }
              </Select>
            </Form.Item>
            <Form.Item name="keyWord" >
              <Input></Input>
            </Form.Item>
            <Space>
              <Button type='primary' htmlType="submit">搜索</Button>
              <Button htmlType='button' onClick={resetFilter}>重置</Button>
            </Space>
          </Form>
        </Space>
      </div>
      <Table
        rowSelection={{
          type: "checkbox",
          onChange: tableSelectionChange,
        }}
        style={{ marginTop: "20px" }}
        columns={columns}
        dataSource={tableDatas}
        pagination={{
          total,
          current: pageParams.page,
          pageSize: pageParams.size,
          ///这里有问题分页列表没有渲染出来
          onChange: paginationChange
        }}
      />
      <Modal title="新增" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form form={formUpdate}>
          <Form.Item label="所属辖区" name="areaId">
            {areaSelectRender()}
          </Form.Item>
          <Form.Item label="经营类型" name="businessType">
            {businessSelectRender()}
          </Form.Item>
          <Form.Item label="门店名称" name="storeName">
            <Input></Input>
          </Form.Item>
          <Form.Item label="公司名称" name="companyName">
            <Input></Input>
          </Form.Item>
          <Form.Item label="许可证有效期" name="validTime">
            <RangePicker />
          </Form.Item>
          <Form.Item label="门头照片" name="sotreImage">
           
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
